<template>
  <div>
    <div>
      <el-upload
        class="upload-demo"
        action=""
        :on-change="fileHandleChange"
        :auto-upload="false"
        style="width: 200px"
        ref="eluploadRef"
      >
        <el-button type="primary">选择文件</el-button>
      </el-upload>

      <div>
        <el-input
          v-model="twoPrice"
          placeholder="请输入二层加价"
          style="width: 200px"
        ></el-input>
        <el-input
          v-model="threePrice"
          placeholder="请输入三层加价"
          style="width: 200px"
        ></el-input>
        <el-input
          v-model="fourPrice"
          placeholder="请输入四层加价"
          style="width: 200px"
        ></el-input>
        <el-input
          v-model="fivePrice"
          placeholder="请输入五层加价"
          style="width: 200px"
        ></el-input>
        <el-button
          type="primary"
          v-if="tableData && tableData.length > 0"
          :disabled="tableData.length < 1"
          @click="toJiaJia"
          >计算纸质加价价格</el-button
        >
      </div>
      <el-button type="primary" @click="toExport">导出文件</el-button>
      <el-button type="primary" @click="toExportKeHu">生成客户价格单</el-button>
      <el-button type="primary" @click="toZhuanHua">直接转化纸质价格</el-button>
      <el-button
        type="primary"
        v-if="tableData && tableData.length > 0"
        :disabled="tableData.length < 1"
        @click="toClear"
        >清空数据</el-button
      >
    </div>
    <div
      style="width: 100%; margin-top: 30px; height: 500px; overflow: auto"
      v-if="tableData && tableData.length > 0"
    >
      <el-table border :data="tableData" height="500px">
        <el-table-column prop="序号" label="序号" />
        <el-table-column prop="纸质编号" label="纸质编号" />
        <el-table-column prop="mzp" label="面纸价格" />
        <el-table-column prop="wz1p" label="瓦纸1" />
        <el-table-column prop="xzp" label="芯纸" />
        <el-table-column prop="wz2p" label="瓦纸2" />
        <el-table-column prop="lzp" label="里纸价格" />
        <el-table-column prop="price" label="未加价总价" />
        <el-table-column prop="jiajia" label="加价"> </el-table-column>
        <el-table-column prop="jiajiaSum" label="加价后总价" />
        <el-table-column prop="hanshuiPrice" label="含税总价" />
      </el-table>
    </div>
  </div>
</template>

<script setup>
import costInfo from "../cost/costInfo";
import { add, floor, toUpper } from "lodash";
import { ElMessage } from "element-plus";
import * as XLSX from "xlsx";
let fileTemp = ref(null);
let tableData = ref([]);
let indexList = [1, 2, 3, 4, 5, 6, 7, 8];
let threePrice = ref(0);
let fivePrice = ref(0);
let twoPrice = ref(0);
let fourPrice = ref(0);

let eluploadRef = ref();
const toClear = () => {
  fileTemp.value = null;
  tableData.value = [];
  eluploadRef.value.clearFiles();
};
const fileHandleChange = (file, fileList) => {
  fileTemp.value = file.raw;
  if (fileTemp.value) {
    if (
      fileTemp.value.type ==
        "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" ||
      fileTemp.value.type == "application/vnd.ms-excel"
    ) {
      importfxx(fileTemp.value);
    } else {
      ElMessage.warning({
        type: "warning",
        message: "附件格式错误，请删除后重新上传！",
      });
    }
  } else {
    ElMessage.warning({
      type: "warning",
      message: "请上传附件！",
    });
  }
};
/**
 * 导入文件
 */
const importfxx = (val) => {
  const reader = new FileReader();
  reader.onload = (e) => {
    const data = new Uint8Array(e.target.result);
    const workbook = XLSX.read(data, { type: "array" });
    const worksheet = workbook.Sheets[workbook.SheetNames[0]];
    const jsonData = XLSX.utils.sheet_to_json(worksheet, { header: 1 });
    tableData.value = getDataByIndexArray(jsonData, indexList);
    console.log(tableData.value);
    tableData.value.forEach((item) => {
      const newPriceInfo = cost(item);
      item.mzp = newPriceInfo.mzp;
      item.lzp = newPriceInfo.lzp;
      item.wz1p = newPriceInfo.wz1p;
      item.wz2p = newPriceInfo.wz2p;
      item.xzp = newPriceInfo.xzp;
      item.price = newPriceInfo.price;

      item.mZhi = newPriceInfo.mZhi;
      item.lZhi = newPriceInfo.lZhi;
      item.wZhi1 = newPriceInfo.wZhi1;
      item.wZhi2 = newPriceInfo.wZhi2;
      item.xZhi = newPriceInfo.xZhi;
    });
  };
  reader.readAsArrayBuffer(val);
};
//导出文件
const toExport = () => {
  let headData = [
    [
      "纸质编号",
      "面纸价格",
      "瓦纸1价格",
      "芯纸价格",
      "瓦纸2价格",
      "里纸价格",
      "未加价总价",
      "加价",
      "加价后总价",
      "含税总价",
    ], //导出表头
  ]; // 表格表头
  tableData.value.forEach((item, index) => {
    let rowData = [];
    //导出内容的字段
    rowData = [
      item.纸质编号,
      item.mzp,
      item.wz1p,
      item.xzp,
      item.wz2p,
      item.lzp,
      item.price,
      item.jiajia,
      item.jiajiaSum,
      item.hanshuiPrice,
    ];
    headData.push(rowData);
  });
  let workSheet = XLSX.utils.aoa_to_sheet(headData);
  let bookNew = XLSX.utils.book_new();
  XLSX.utils.book_append_sheet(bookNew, workSheet, "作品名称"); // 工作簿名称
  let currentTimestampInSeconds = Date.now();
  let name = "新报价单" + currentTimestampInSeconds + ".xlsx";
  XLSX.writeFile(bookNew, name);
};
//导出客户表单
const toExportKeHu = () => {
  let headData = [
    ["面纸", "E", "B", "C", "芯纸", "里纸", "总价", "含税总价"], //导出表头, //导出表头
  ]; // 表格表头
  tableData.value.forEach((item, index) => {
    console.log(item);
    let rowData = [];
    let eLeng = "";
    let bLeng = "";
    let cLeng = "";
    let xLeng = "";
    if (lengxingList.includes(item.xZhi.charAt(item.xZhi.length - 1))) {
      let lengxing = item.xZhi.slice(-1);
      if (lengxing == "E") {
        eLeng = item.xZhi.slice(0, -2);
      } else if (lengxing == "B") {
        bLeng = item.xZhi.slice(0, -2);
      } else if (lengxing == "C") {
        cLeng = item.xZhi.slice(0, -2);
      }
    } else {
      let lengxing1 = item.wZhi1.slice(-1);
      let lengxing2 = item.wZhi2.slice(-1);
      if (lengxing1 == "E") {
        eLeng = item.wZhi1.slice(0, -2);
      } else if (lengxing1 == "B") {
        bLeng = item.wZhi1.slice(0, -2);
      }
      if (lengxing2 == "B") {
        bLeng = item.wZhi2.slice(0, -2);
      } else if (lengxing2 == "C") {
        cLeng = item.wZhi2.slice(0, -2);
      }
      xLeng = item.xZhi;
    }
    console.log(eLeng, bLeng, cLeng, xLeng);
    //导出内容的字段
    rowData = [
      item.mZhi,
      eLeng,
      bLeng,
      cLeng,
      xLeng,
      item.lZhi,
      item.jiajiaSum,
      item.hanshuiPrice,
    ];
    headData.push(rowData);
  });
  let workSheet = XLSX.utils.aoa_to_sheet(headData);
  let bookNew = XLSX.utils.book_new();
  XLSX.utils.book_append_sheet(bookNew, workSheet, "作品名称"); // 工作簿名称
  let currentTimestampInSeconds = Date.now();
  let name = "新报价单" + currentTimestampInSeconds + ".xlsx";
  XLSX.writeFile(bookNew, name);
};
//直接转化
const toZhuanHua = () => {
  let headData = [
    ["面纸", "E楞", "B楞", "C楞", "芯纸", "里纸", "总价"], //导出表头, //导出表头
  ]; // 表格表头
  tableData.value.forEach((item, index) => {
    console.log(item);
    let rowData = [];
    let eLeng = "";
    let bLeng = "";
    let cLeng = "";
    let xLeng = "";
    if (lengxingList.includes(item.xZhi.charAt(item.xZhi.length - 1))) {
      let lengxing = item.xZhi.slice(-1);
      if (lengxing == "E") {
        eLeng = item.xZhi.slice(0, -2);
      } else if (lengxing == "B") {
        bLeng = item.xZhi.slice(0, -2);
      } else if (lengxing == "C") {
        cLeng = item.xZhi.slice(0, -2);
      }
    } else {
      let lengxing1 = item.wZhi1.slice(-1);
      let lengxing2 = item.wZhi2.slice(-1);
      if (lengxing1 == "E") {
        eLeng = item.wZhi1.slice(0, -2);
      } else if (lengxing1 == "B") {
        bLeng = item.wZhi1.slice(0, -2);
      }
      if (lengxing2 == "B") {
        bLeng = item.wZhi2.slice(0, -2);
      } else if (lengxing2 == "C") {
        cLeng = item.wZhi2.slice(0, -2);
      }
      xLeng = item.xZhi;
    }
    console.log(eLeng, bLeng, cLeng, xLeng);
    //导出内容的字段
    rowData = [item.mZhi, eLeng, bLeng, cLeng, xLeng, item.lZhi, item.报价];
    headData.push(rowData);
  });
  let workSheet = XLSX.utils.aoa_to_sheet(headData);
  let bookNew = XLSX.utils.book_new();
  XLSX.utils.book_append_sheet(bookNew, workSheet, "纸质报价"); // 工作簿名称
  let currentTimestampInSeconds = Date.now();
  let name = "客户报价单" + currentTimestampInSeconds + ".xlsx";
  XLSX.writeFile(bookNew, name);
};
/**
 * 整理的数据
 * @param data
 * @param indexArray
 */
function getDataByIndexArray(data, indexArray) {
  const result = [];
  for (let i = 1; i < data.length; i++) {
    const row = data[i];
    const rowData = {};
    for (let j = 0; j < indexArray.length; j++) {
      const index = indexArray[j];
      rowData[data[0][index]] = row[index];
    }
    result.push(rowData);
  }
  return result;
}
const lengxingList = ["B", "C", "F", "E", "EB", "BC"]; //楞型
const mianZhiList = ["A", "Q", "T", "W", "D","F"]; //面纸
const cost = (item) => {
  let mZhiPrice = ref("");
  let lZhiPrice = ref("");
  let wZhi1Price = ref("");
  let wZhi2Price = ref("");
  let xZhiPrice = ref("");

  const tranCode = toUpper(item.纸质编号.trim()).replace(/\s/g, ""); //去除空格转大写的code
  console.log(tranCode);
  let index = tranCode.indexOf("/");

  let lengXing = tranCode.substring(index + 1, tranCode.length);
  let zhizhi = tranCode.substring(0, index); //纸质
  let mianZhi = ""; //面纸
  let liZhi = ""; //里纸
  let walengXin = ""; //瓦楞芯纸字符串
  let walengxinList = []; //瓦楞芯纸列表
  let lengXingList = []; //瓦楞列表
  let sumPrice = 0; //总价格
  let mZhi = "";
  let lZhi = "";
  let wZhi1 = "";
  let wZhi2 = "";
  let xZhi = "";

  //拆分纸质

  //获取是否有面纸，确实是二四  还是三五
  const firstChar = tranCode.charAt(0);
  if (mianZhiList.includes(firstChar)) {
    mianZhi = tranCode.substring(0, 2);
  } else {
    mianZhi = "";
  }
  //获取里纸型号
  liZhi = findLizhi(zhizhi);
  //获取瓦楞和夹心
  walengXin = trimStartAndEnd(zhizhi, mianZhi, liZhi);
  //拆分瓦楞和芯纸
  walengxinList = walengXin.split("");
  lengXingList = lengXing.split("");
  //面纸价格
  mZhi = getPriceByNoAndName(mianZhi);
  mZhiPrice = getPriceByNoAndType(mianZhi);
  sumPrice = add(sumPrice, getPriceByNoAndType(mianZhi));
  //里纸价格
  lZhi = getPriceByNoAndName(liZhi);
  lZhiPrice = getPriceByNoAndType(liZhi);
  sumPrice = add(sumPrice, getPriceByNoAndType(liZhi));
  //瓦楞芯纸价格
  if (lengXingList.length > 1) {
    walengxinList.forEach((item, index) => {
      if (index == 0) {
        //瓦楞1的价格
        wZhi1 = getPriceByNoAndName(item) + "/" + lengXingList[0];
        sumPrice = add(sumPrice, getPriceByNoAndType(item, lengXingList[0]));
        wZhi1Price = getPriceByNoAndType(item, lengXingList[0]);
      } else if (index == 2) {
        //瓦楞2的价格
        wZhi2 = getPriceByNoAndName(item) + "/" + lengXingList[1];
        sumPrice = add(sumPrice, getPriceByNoAndType(item, lengXingList[1]));
        wZhi2Price = getPriceByNoAndType(item, lengXingList[1]);
      } else {
        //芯纸的价格
        xZhi = getPriceByNoAndName(item);
        sumPrice = add(sumPrice, getPriceByNoAndType(item));
        xZhiPrice = getPriceByNoAndType(item);
      }
    });
  } else {
    //瓦楞1/芯纸的价格  2,3层夹心瓦楞的价格，如果是两层的E瓦需要单独计算
    walengxinList.forEach((item, index) => {
      xZhi = getPriceByNoAndName(item) + "/" + lengXingList[0];
      if(mianZhi){
        sumPrice = add(sumPrice, getPriceByNoAndType(item, lengXingList[0]));
        xZhiPrice.value = getPriceByNoAndType(item, lengXingList[0]);
      }else{
        sumPrice = add(sumPrice, getPriceByNoAndType(item, lengXingList[0],'KT'));
        xZhiPrice.value = getPriceByNoAndType(item, lengXingList[0],'KT');
      }
    });
  }
  return {
    mZhi: mZhi,
    lZhi: lZhi,
    wZhi1: wZhi1,
    wZhi2: wZhi2,
    xZhi: xZhi,

    mzp: mZhiPrice,
    lzp: lZhiPrice,
    wz1p: wZhi1Price,
    wz2p: wZhi2Price,
    xzp: xZhiPrice,
    price: floor(sumPrice, 3).toFixed(2),
  };
};
//获取对应价格
function getPriceByNoAndType(no, type = "", shengChanXian = "JS") {
  const item = costInfo.find((cost) => cost.no === no);
  if (!item) {
    return null;
  }
  switch (type.toUpperCase()) {
    case "E":
      if (shengChanXian == "KT") {
        return item.e2Price || item.xiubianPrice;
      } else {
        return item.ePrice || item.xiubianPrice;
      }
    case "B":
      return item.bPrice || item.xiubianPrice;
    case "C":
      return item.cPrice || item.xiubianPrice;
      case "F":
      return item.fPrice || item.xiubianPrice;
    default:
      return item.xiubianPrice;
  }
}
//获取对应名称
function getPriceByNoAndName(no) {
  const item = costInfo.find((cost) => cost.no === no);
  if (!item) {
    return null;
  }
  return item.name;
}

//寻找里纸
const findLizhi = (str) => {
  for (let i = str.length - 1; i >= 0; i--) {
    if (/[a-zA-Z]/.test(str[i])) {
      return str.slice(i);
    }
  }
  return null;
};
//获取瓦楞和夹心
function trimStartAndEnd(str, startStr, endStr) {
  let result = str;
  if (startStr && str.startsWith(startStr)) {
    result = result.slice(startStr.length);
  }
  if (endStr && str.endsWith(endStr)) {
    result = result.slice(0, result.length - endStr.length);
  }
  return result;
}
const toJiaJia = () => {
  tableData.value.forEach((item) => {
    let count = 0;
    if (Number(item.mzp) !== 0) {
      count = count + 1;
    }
    if (Number(item.wz1p) !== 0) {
      count = count + 1;
    }
    if (Number(item.xzp) !== 0) {
      count = count + 1;
    }
    if (Number(item.wz2p) !== 0) {
      count = count + 1;
    }
    if (Number(item.lzp) !== 0) {
      count = count + 1;
    }
    if (count === 2) {
      item.jiajia = twoPrice.value;
    } else if (count === 3) {
      item.jiajia = threePrice.value;
    } else if (count === 4) {
      item.jiajia = fourPrice.value;
    } else if (count === 5) {
      item.jiajia = fivePrice.value;
    }
    item.jiajiaSum = myFixed(add(Number(item.price), Number(item.jiajia)), 2);
    item.hanshuiPrice = myFixed(item.jiajiaSum * 1.06, 2);
  });
};
/**
 * 保留小数点几位数, 自动补零, 四舍五入
 * @param num: 数值
 * @param digit: 小数点后位数
 * @returns string
 */
function myFixed(num, digit) {
  if (Object.is(parseFloat(num), NaN)) {
    return console.log(`传入的值：${num}不是一个数字`);
  }
  num = parseFloat(num);
  return (
    Math.round((num + Number.EPSILON) * Math.pow(10, digit)) /
    Math.pow(10, digit)
  ).toFixed(digit);
}
</script>

<style lang="scss" scoped></style>
